package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.enums.workbench.BlockTypeEnum;
import com.xhwl.common.enums.workbench.MyTaskStatusEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.workbench.AccountTask;
import com.xhwl.common.pojo.workbench.BlockCount;
import com.xhwl.common.pojo.workbench.MyTask;
import com.xhwl.common.query.workbanch.MyTaskQuery;
import com.xhwl.data.dao.IMyTaskDao;
import com.xhwl.data.service.IAccountTaskService;
import com.xhwl.data.service.IMyTaskService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 14:30 2021/8/11
 */
@Service
public class MyTaskServiceImpl implements IMyTaskService {

	@Autowired
	private IMyTaskDao myTaskDao;

	@Autowired
	private IAccountTaskService accountTaskService;

	private static final Logger log = LoggerFactory.getLogger(MyTaskServiceImpl.class);

	@Override
	@Transactional
	public ResultJson create(MyTask myTask, List<Integer> accountId) {
		if(null == myTask){
			log.info("空入参");
			return ResultJson.fail("参数错误");
		}
		if(StringUtils.isEmpty(myTask.getUId())){
			log.info("缺少uid");
			return ResultJson.fail("缺少uId");
		}
		if(StringUtils.isEmpty(myTask.getTitle())){
			log.info("缺少title");
			return ResultJson.fail("缺少title");
		}
		if(StringUtils.isEmpty(myTask.getContent())){
			log.info("缺少content");
			return ResultJson.fail("缺少content");
		}
		if(myTask.getContent().length() > 200){
			myTask.setContent(myTask.getContent().substring(0, 200) + "...");
		}
		if(null == myTask.getBlockType()){
			log.info("缺少blockType");
			return ResultJson.fail("缺少blockType");
		}
		if(null == myTask.getBlockStatus()){
			log.info("缺少任务状态");
			return ResultJson.fail("缺少任务状态");
		}
		if(null == myTask.getStatus()){
			log.info("缺少我的任务状态校验");
			return ResultJson.fail("缺少我的任务状态，代办 or 与我相关");
		}
		QueryWrapper<MyTask> myTaskQueryWrapper = new QueryWrapper<>();
		myTaskQueryWrapper.eq("u_id", myTask.getUId());
		myTaskQueryWrapper.eq("block_type", myTask.getBlockType());
		List<MyTask> myTasks = myTaskDao.selectList(myTaskQueryWrapper);
		// 一条任务在一个人的状态要么是与我相关，要么待办，不存在一条任务既是这个人的待办有是这个人的相关
		if(CollectionUtils.isNotEmpty(myTasks)){
			// 更新 这里只更新状态和关联的人
			MyTask original = myTasks.get(0);
			original.setBlockStatus(myTask.getBlockStatus());
			original.setStatus(myTask.getStatus());
			myTask.setId(original.getId());
			myTaskDao.updateById(original);
			// 关联的人
			QueryWrapper<AccountTask> accountTaskQueryWrapper = new QueryWrapper<>();
			accountTaskQueryWrapper.eq("task_id", original.getId());
			List<AccountTask> list = accountTaskService.list(accountTaskQueryWrapper);
			if(CollectionUtils.isNotEmpty(list)){
				// 之前任务绑定的账号
				List<Integer> old = list.stream().map(l -> l.getAccountId()).collect(Collectors.toList());
				if(CollectionUtils.isNotEmpty(accountId)){
					// 新传入的账号
					List<Integer> collect1 = accountId.stream().collect(Collectors.toList());
					// 先取交集
					List<Integer> list1 = collect1.stream().filter( c -> old.contains(c)).collect(Collectors.toList());
					if(CollectionUtils.isNotEmpty(list1)){
						// 账号已经关联任务的更新为新传入的任务状态
						List<AccountTask> collect = list.stream().filter(l -> list1.contains(l.getAccountId())).collect(Collectors.toList());
						for (AccountTask accountTask : collect) {
							accountTask.setStatus(myTask.getStatus());
						}
						accountTaskService.updateBatchById(collect);
					}
					// 需要更新为与我相关的集合
					List<Integer> collect = old.stream().filter(o -> !collect1.contains(o)).collect(Collectors.toList());
					collect1.removeAll(old);
					// 全部需要新增的集合
					accountId = collect1;
					// 老任务（没有涉及更改的）状态变更为 与我相关
					list = list.stream().filter(l -> collect.contains(l.getAccountId())).collect(Collectors.toList());
				}
				if(CollectionUtils.isNotEmpty(list)){
					for (AccountTask accountTask : list) {
						accountTask.setStatus(MyTaskStatusEnum.ABOUT);
					}
					accountTaskService.updateBatchById(list);
				}
			}
		}else{
			// 新增
			myTaskDao.insert(myTask);
		}
		if(CollectionUtils.isNotEmpty(accountId)){
			accountId = accountId.stream().distinct().collect(Collectors.toList());
			List<AccountTask> accountTasks = new ArrayList<>(accountId.size());
			for (Integer integer : accountId) {
				AccountTask accountTask = new AccountTask();
				accountTask.setAccountId(integer);
				accountTask.setTaskId(myTask.getId());
				accountTask.setStatus(myTask.getStatus());
				accountTasks.add(accountTask);
			}
			accountTaskService.saveBatch(accountTasks);
		}
		return ResultJson.success();
	}

	@Override
	public Page<MyTask> page(MyTaskQuery myTaskQuery, Page page) {
		return myTaskDao.page(page, myTaskQuery);
	}

	@Override
	public List<BlockCount> countBlockType(MyTaskQuery myTaskQuery) {
		BlockTypeEnum[] values = BlockTypeEnum.values();
		List<BlockCount> blockCounts = new ArrayList<>(values.length);
		for (BlockTypeEnum value : values) {
			BlockCount blockCount = new BlockCount();
			blockCount.setBlockType(value);
			myTaskQuery.setBlockType(value);
			blockCount.setCount(myTaskDao.count(myTaskQuery));
			blockCounts.add(blockCount);
		}
		return blockCounts;
	}
}
